class App{
    static run(){
        const http = require('http')

        // 创建http服务并开启80端口监听
        http.createServer((req, resp) => {
            try {
                router(req, resp)
            } catch (error) {
                resp.statusCode = 404
                resp.end('404 not found')
            }
            
        }).listen(80, () => {
            console.log('server running at http://127.0.0.1')
        })
    }
}

function router(req, resp){
    const path = require('path')

    const rootpath = path.join(__dirname, '../')

    const urlObj = new URL(req.url, 'http://127.0.0.1')
    const pathname = urlObj.pathname
    const partPath = pathname.split('/')

    let controllerName = 'index'
    let method = 'index'

    console.log(rootpath)
    
    if (partPath.length == 3){
        controllerName = partPath[1]
        method = partPath[2]
    }

    const controllerPath = path.join(rootpath, `./app/controller/${controllerName}.js`)
    console.log(controllerPath)
    const controllerObj = require(controllerPath)

    new controllerObj()[method](resp)
}

module.exports = App